package utgame.com.broadcastdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import utgame.com.basedemo.BaseActivity;

// 动态注册广播接收器
public class BroadCastActivity extends BaseActivity implements View.OnClickListener{

    private IntentFilter intentFilter;
    private NetworkChangeReceiver networkChangeReceiver;

    private Button mBtnSendBroadCast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_broad_cast);
        baseSetContentView(R.layout.activity_broad_cast);

        initView();

        intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        networkChangeReceiver = new NetworkChangeReceiver();
        registerReceiver(networkChangeReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(networkChangeReceiver);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_send_broadcast){
            Intent intent = new Intent("utgame.com.broadcastdemo.XAN_BROADCAST");
            sendBroadcast(intent);
        }
    }


    private void initView(){
        mBtnSendBroadCast = (Button)findViewById(R.id.btn_send_broadcast);
        mBtnSendBroadCast.setOnClickListener(this);
    }

    class NetworkChangeReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {


            ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()){
                writeLog("network is available\n", true);
            } else {
                writeLog("network is not available\n", true);
            }

        }
    }

}
